/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#ifndef __SIMPLEARRAY_H__
#define __SIMPLEARRAY_H__

#include <utility>
#include <algorithm>

namespace liba
{

template<class T>
class SimpleArray
{
public:
	typedef size_t size_type;
	typedef ptrdiff_t difference_type;
	typedef T & reference;
	typedef const T & const_reference;
	typedef T value_type;
	typedef T * pointer;
	typedef const T * const_pointer;
	typedef pointer iterator;
	typedef const_pointer const_iterator;

	SimpleArray( size_type si, const T & v )
	:	si( si ),
		da( new T[si] )
	{
		std::fill( begin(), end(), v );
	}
	explicit SimpleArray( size_type si )
	:	si( si ),
		da( new T[ si ] )
	{}
	SimpleArray()
	:	si( 0 ),
		da( 0 )
	{}
	virtual ~SimpleArray()
	{
		delete [] da; da = 0;
	}
	SimpleArray( const SimpleArray<T> & a )
	:	si( a.si ),
		da( new T[ a.si ] )
	{
		std::copy( a.begin(), a.end(), begin() );
	}
	const SimpleArray & operator= ( const SimpleArray<T> & a )
	{
		if( this != &a )
		{
			delete [] da; da = 0;
			si = a.si;
			da = new T[ si ];
			std::copy( a.begin(), a.end(), begin() );
		}
		return *this;
	}
	
	T & operator[]( size_type x )
	{
		return da[ x ];
	}

	const T & operator[]( size_type x )const
	{
		return da[ x ];
	}

	size_type size()const
	{
		return si;
	}
	T * data()
	{
		return da;
	}
	const T * data()const
	{
		return da;
	}
	void resize( size_t new_size )
	{
		T * old_data = da;
		size_t old_size = si;
		si = new_size;
		da = new T[ new_size ];
		std::copy( old_data, old_data + std::min(old_size,new_size), da );
		delete [] old_data; old_data = 0;
	}
	void resize( size_t new_size, T v )
	{
		T * old_data = da;
		size_t old_size = si;
		si = new_size;
		da = new T[ new_size ];
		std::copy( old_data, old_data + std::min(old_size,new_size), da );
		if( new_size > old_size )
			std::fill( da + old_size, da + new_size, v );
		delete [] old_data; old_data = 0;
	}
	void clear()
	{
		delete [] da; da = 0;
		si = 0;
	}
	const_iterator begin()const
	{
		return da;
	}
	iterator begin()
	{
		return da;
	}
	const_iterator end()const
	{
		return da + si;
	}
	iterator end()
	{
		return da + si;
	}
private:
	size_t si;
	T * da;
};

} // namespace liba
using namespace liba;


#endif //__SIMPLEARRAY_H__